﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.ManagementConsole;

namespace SharpShare.Management.Mmc.Views {
    public class PropertyGridPropertyPage : PropertyPage {
        private Dictionary<PropertyDescriptor, object> _originalValues = new Dictionary<PropertyDescriptor, object>();

        public event EventHandler Applied;
        public event EventHandler Cancelled;

        public PropertyGridPropertyPage(object editObject) {
            this.EditObject = editObject;

            PropertyGrid grid = new PropertyGrid();
            grid.Dock = DockStyle.Fill;
            grid.PropertySort = PropertySort.CategorizedAlphabetical;
            grid.CommandsVisibleIfAvailable = true;
            grid.Size = new Size(410, 450);
            grid.PropertyValueChanged += new PropertyValueChangedEventHandler(PropertyGridPropertyValueChanged);
            grid.Font = new Font("Tahoma", 8.0f);
            grid.SelectedObject = this.EditObject;

            this.Control = grid;
        }

        public object EditObject { get; private set; }

        protected override void OnInitialize() {
            base.OnInitialize();


        }

        protected override bool OnOK() {
            _originalValues.Clear();
            this.Dirty = false;

            this.OnApplied();

            return true;
        }
        protected override bool OnApply() {
            _originalValues.Clear();
            this.Dirty = false;

            this.OnApplied();

            return true;
        }

        protected override void OnCancel() {
            base.OnCancel();

            foreach (PropertyDescriptor descriptor in _originalValues.Keys) {
                object origValue = _originalValues[descriptor];
                descriptor.SetValue(this.EditObject, origValue);
            }

            this.OnCancelled();
        }
        protected override void OnSetActive() {
            base.OnSetActive();

            try {
                this.Control.Parent.Font = this.Control.Font;
            } catch { }
        }

        private void PropertyGridPropertyValueChanged(object s, PropertyValueChangedEventArgs e) {
            if (!_originalValues.ContainsKey(e.ChangedItem.PropertyDescriptor)) {
                _originalValues[e.ChangedItem.PropertyDescriptor] = e.OldValue;
            }

            this.Dirty = true;
        }

        private void OnCancelled() {
            if (Cancelled != null) {
                try {
                    Cancelled(this, EventArgs.Empty);
                } catch { }
            }
        }

        private void OnApplied() {
            if (Applied != null) {
                try {
                    Applied(this, EventArgs.Empty);
                } catch { }
            }
        }
    }
}
